import Tabs, { TabsProps } from '@/components/Tabs';
import React, { useRef, useState } from 'react';

import BaseInfo from './components/BaseInfo';
import OrganizationalAuthority from './components/OrganizationalAuthority';

import { sysOrgControllerOrgInfo } from '@/services/ess/sysOrg';
import { useIntl } from 'umi';
import TreeList from './components/Tree2';
import Styles from './index.less';

const App: React.FC = () => {
  const [baseInfo, setBaseInfo] = useState(null);
  const [fliterTreeData, setfliterTreeData] = useState([]);
  const [orgId, setOrgId] = useState<any>('');
  const [activeKey, setActiveKey] = useState('1');
  const treeRefs = useRef();
  const intl = useIntl();

  const fliters = (tree: any, id: number) => {
    return tree
      .map((node: any) => {
        if (node.id === id) {
          return null; // 返回 null 表示删除该节点
        } else if (node.children && node.children.length) {
          return {
            ...node,
            children: fliters(node.children, id),
          };
        } else {
          return node;
        }
      })
      .filter(Boolean); // 过滤掉返回的 null 值
  };

  const treeClick = (id: number, TreeALL: any) => {
    if (id) {
      setOrgId(id);
      const filteredTree = fliters(TreeALL, id); // 对原始 TreeALL 进行过滤
      console.log(filteredTree, TreeALL);
      setfliterTreeData(filteredTree);
      sysOrgControllerOrgInfo({ orgId: id }).then((res: any) => {
        setBaseInfo(res.data);
      });
    }
  };

  const deleteCall = () => {
    setOrgId('');
    setBaseInfo(null);
  };

  const handleBaseInfo = (res: boolean) => {
    if (res) {
      treeRefs.current.queryTreeList();
    }
  };

  const items: TabsProps['items'] = [
    {
      label: intl.formatMessage({
        id: 'systemManagement.organizationalManagementMenu.essentialInformation',
      }),
      key: '1',
    },
    {
      label: intl.formatMessage({
        id: 'systemManagement.organizationalManagementMenu.organizationNumber',
      }),
      key: '2',
    },
  ];

  return (
    <div className={Styles.OrgWrap}>
      <Tabs
        items={items}
        className={Styles.tabs}
        onChange={(key: string) => {
          setActiveKey(key);
        }}
      />
      <div className={Styles.contentWrap}>
        <div className={Styles.left}>
          <TreeList handleClick={treeClick} deleteCall={deleteCall} ref={treeRefs} />
        </div>
        <div className={Styles.right}>
          {activeKey === '1' ? (
            <BaseInfo
              baseInfo={baseInfo}
              handleBaseInfo={handleBaseInfo}
              fliterTreeData={fliterTreeData}
            />
          ) : (
            <OrganizationalAuthority orgId={orgId} />
          )}
        </div>
      </div>
    </div>
  );
};

export default App;
